const app = getApp();

Page({
  data: {
    inputVisible: false,
    newCategoryName: '',
    categories: [],
    rows: [],
  },

  onLoad: function() {
    this.loadCategories();
  },

  onShow: function() {
    this.loadCategories();
  },

  loadCategories: function() {
    const categories = app.globalData.categories || [];
    this.setData({
      categories,
      rows: this.updateRows(categories),
    });
  },

  updateRows: function(categories) {
    const rows = [];
    for (let i = 0; i < categories.length; i += 4) {
      rows.push(categories.slice(i, i + 4));
    }
    return rows;
  },

  onDeleteCategory: function(id) {
    const app = getApp();
    const originalCategories = app.globalData.categories;
    const updatedCategories = originalCategories.filter(category => category.id !== id);
    
    // 检查更新后的分类列表是否非空
    if (updatedCategories.length > 0) {
      app.globalData.categories = updatedCategories;
      this.setData({
        categories: updatedCategories,
        rows: this.updateRows(updatedCategories),
      });
      wx.setStorageSync('categories', updatedCategories);
    }
  },

  onAddTap: function() {
    wx.showModal({
      title: '添加新分类',
      content: '请输入新分类的名称',
      editable: true,
      success: (res) => {
        if (res.confirm) {
          const newCategoryName = res.content.trim();
          if (newCategoryName) {
            this.addCategory(newCategoryName);
          }
        }
      },
    });
  },

  addCategory: function(newCategoryName) {
    const newCategory = {
      id: Date.now(),
      name: newCategoryName,
      icon: '/staic/0 (2).png',
    };
    app.globalData.categories.push(newCategory);
    this.setData({
      categories: app.globalData.categories,
      rows: this.updateRows(app.globalData.categories),
      inputVisible: false,
      newCategoryName: '',
    });
    wx.setStorageSync('categories', app.globalData.categories);
  },

  onItemLongPress: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.showActionSheet({
      itemList: ['删除分类'],
      itemColor: '#333',
      success: (res) => {
        if (!res.cancel && res.tapIndex === 0) {
          this.onDeleteCategory(id);
        }
      },
      fail: function(res) {
        console.log('显示操作菜单失败', res);
      },
    });
  },

  onInput: function(e) {
    this.setData({
      newCategoryName: e.detail.value
    });
  },

  onConfirm: function(e) {
    if (this.data.newCategoryName.trim()) {
      this.onAddTap();
    }
    this.setData({
      inputVisible: false,
      newCategoryName: ''
    });
  },
});